package org.intertwine.grurly.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Created by IntelliJ IDEA.
 * User: Stian Lindhom
 * Date: 20.mar.2010
 * Time: 14:26:02
 * To change this template use File | Settings | File Templates.
 */

public class ShortUrlFilter implements Filter {
    public void destroy() {
    }

    /**
     * If the request is for a sub path, pass the request through the filter chain to serve static resources
     * otherwise set the key as a attribute and dispatch to the index.groovy script
     *
     * @param req
     * @param resp
     * @param chain
     * @throws ServletException
     * @throws IOException
     */
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest hreq = (HttpServletRequest) req;
        String subPathRegex = "\\/(\\w.*)\\/(\\w.*)";
        if (hreq.getRequestURI().matches(subPathRegex)) {
            chain.doFilter(req, resp);
        } else {
            hreq.setAttribute("key", hreq.getRequestURI().substring(1));
            hreq.getRequestDispatcher("/index.groovy").forward(req, resp);
        }
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
